import { reactive } from "vue";
import { createRouter, createWebHashHistory } from "vue-router";
import NProgress from "@/utils/system/nprogress";
import { changeTitle } from "@/utils/system/title";
import pinia from "@/store/index.js";
import useKeepAliveStore from "@/store/modules/keepAlive.js";

// 引入不需要权限的modules
import main from "./modules/main";
import home from "./modules/home";

NProgress.configure({ showSpinner: false });

/**
 * @name 初始化必须要的路由
 * @description 使用reactive属性使得modules可以在路由菜单里面实时响应，搞定菜单回显的问题
 * @detail 针对modules的任何修改，均会同步至菜单级别，记住，是针对变量名为：moduels的修改
 **/
const modules = reactive([...main, ...home]);

const router = createRouter({
  history: createWebHashHistory(),
  routes: modules,
});

// 未授权时可访问的白名单
const whiteList = ["/login", "/main", "/home/delicacy"];

const useKeepAlive = useKeepAliveStore(pinia);

// 路由跳转前的监听操作
router.beforeEach((to, _from, next) => {
  NProgress.start();
  // store.state.user.token
  if (true) {
    to.meta.title ? changeTitle(to.meta.title) : ""; // 动态title
    if (to.path === "/login") {
      next("/");
      return;
    }
    next();
  } else if (whiteList.includes(to.path)) {
    to.meta.title ? changeTitle(to.meta.title) : ""; // 动态title
    next();
  } else {
    next("/login"); // 全部重定向到登录页
    to.meta.title ? changeTitle(to.meta.title) : ""; // 动态title
  }
});

// 路由跳转后的监听操作
router.afterEach((to, _from) => {
  const keepAliveComponentsName = useKeepAlive.getKeepAliveComponentsName || [];
  const name = to.matched[to.matched.length - 1].components.default.name || "";
  if (
    to.meta &&
    to.meta.cache &&
    name &&
    !keepAliveComponentsName.includes(name)
  ) {
    useKeepAlive.addKeepAliveComponentsName(name);
  }
  NProgress.done();
});

export { modules };

export default router;
